package com.example.client.controller.user;

import com.example.commentservice.service.CommentService;
import com.example.commonapi.constant.UserStatus;
import com.example.commonapi.dto.Status;
import com.example.commonapi.dto.UpdatePasswordDTO;
import com.example.commonapi.dto.UserStatusDTO;
import com.example.commonapi.pojo.Topic;
import com.example.commonapi.pojo.User;
import com.example.topicservice.service.TopicService;
import com.example.userservice.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class UserRestController {
    private static final Log logger = LogFactory.getLog(UserRestController.class);
    @Reference(version = "${demo.service.version}")
    TopicService topicService;
    @Reference(version = "${demo.service.version}")
    UserService userService;
    @Reference(version = "${demo.service.version}")
    CommentService commentService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 删除用户
     *
     * @param user
     * @param request
     * @return
     */
    @PostMapping("/user/delete")
    public String userDelete(@RequestBody User user, HttpServletRequest request) {
        List<Topic> topics = topicService.getTopicByUserId(user.getId());

        // 删除所有的评论
        for (Topic topic : topics)
            commentService.deleteCommentByTopicId(topic.getId());
        topicService.deleteTopicByUserId(user.getId());
        userService.deleteUser(user.getId());

        request.getSession().removeAttribute("user");

        return "1";
    }

    /**
     * 注册
     *
     * @param user
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("/register")
    public String register(@RequestBody User user, HttpServletRequest request) throws JsonProcessingException {
        Status status = new Status();

        if (userService.existUsername(user.getUsername())) {
            status.setStatus(UserStatus.USER_EXIST.getStatus());
            return objectMapper.writeValueAsString(status);
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time = new Date();
        user.setTime(formatter.format(time));
        userService.addUser(user);

        status.setStatus(UserStatus.USER_REGISTER_SUCCESS.getStatus());

        //  将用户消息保存到 Session
        HttpSession session = request.getSession();
        session.setAttribute("user", userService.getUserByUsername(user.getUsername()));

        return objectMapper.writeValueAsString(status);
    }

    /**
     * 登录
     *
     * @param user
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("/login")
    public String login(@RequestBody User user, HttpServletRequest request) throws JsonProcessingException {
        UserStatusDTO userStatus = new UserStatusDTO();

        User user2 = userService.getUserByUsername(user.getUsername());
        if (user2 != null) {
            if (user2.getPassword().equals(user.getPassword())) {
                userStatus.setStatus(UserStatus.USER_LOGIN_SUCCESS.getStatus());
                //  将用户消息保存到 Session
                HttpSession session = request.getSession();
                session.setAttribute("user", user2);
            } else
                userStatus.setStatus(UserStatus.USER_LOGIN_FAILURE.getStatus());
        }

        userStatus.setUser(user);

        return objectMapper.writeValueAsString(userStatus);
    }

    /**
     * 获取所有用户
     *
     * @return
     */
    @GetMapping("/user/get/total")
    public String userGetTotal() throws JsonProcessingException {
        List<User> users = userService.totalUser();
        return objectMapper.writeValueAsString(users);
    }

    /**
     * 修改密码
     *
     * @param passwordDTO
     * @param request
     * @return
     * @throws JsonProcessingException
     */
    @PutMapping("/user/password")
    public String updatePassword(
            @RequestBody UpdatePasswordDTO passwordDTO,
            HttpServletRequest request
    ) throws JsonProcessingException {
        // 获取保存在 session 中的用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        // 创建返回状态
        Status status = new Status();

        // 判断旧密码是否错误
        if (user.getPassword().equals(passwordDTO.getOldPassword())) {
            // 对了，则进行更改
            userService.updateUserPassword(user.getUsername(), passwordDTO.getNewPassword());
            // 去除session数据
            session.removeAttribute("user");
            status.setStatus(UserStatus.USER_UPDATE_PASSWORD_SUCCESS.getStatus());
        } else {
            // 错了直接返回
            status.setStatus(UserStatus.USER_OLD_PASSWORD_FAILURE.getStatus());
        }

        return objectMapper.writeValueAsString(status);
    }
}
